(function(){
  function Snake(option) {
    // 蛇的属性，蛇头、蛇身体的宽高及其颜色、蛇的位置x，y,蛇运动的方向
    this.option = this.option instanceof Object ? option : {};
    this.width = this.option.width || 20;
    this.height = this.option.height || 20;
    // 蛇头和蛇的身体储存在数组里，初始位置
    this.body = [
      {x: 3, y: 2, color:"red"},
      {x: 2, y :2, color:"blue"},
      {x: 1, y: 2, color:"blue"}
    ]
    // 初始运动方向为向右运动
    this.direction = "right";
    // 记录蛇节的数组
    this.eles = [];
  }
  var ps = "absolute";
  Snake.prototype.render = function(map) {
    for(var i = 0, len = this.body.length; i < len; i++) {
      var ele = document.createElement("div");
      ele.style.width = this.width + "px";
      ele.style.height = this.height + "px";
      ele.style.left = this.body[i].x * this.width + "px";
      ele.style.top = this.body[i].y * this.height + "px";
      ele.style.backgroundColor = this.body[i].color;
      ele.style.position = ps;
      map.appendChild(ele);
      this.eles.push(ele);
    }
  }
  // 蛇移动
  Snake.prototype.move = function() {
    // 蛇运动时，每一节都会变成上一节的位置
    for(var i = this.body.length - 1; i > 0; i--) {
      this.body[i].x = this.body[i-1].x;
      this.body[i].y = this.body[i-1].y;
    }
    // 蛇头的方向根据方向变化，蛇头的位置是this.body[0]
    var head = this.body[0];
    switch(this.direction) {
      case "right":
        head.x ++;
        break;
      case "left":
        head.x --;
        break;
      case "up":
        head.y --;
        break;
      case "down":
        head.y ++;
        break;
    }
  }
  // 删除蛇节的方法
  Snake.prototype.del = function (map) {
    // 删除元素
    for (var i = this.eles.length - 1; i >= 0 ; i--) {
      map.removeChild(this.eles[i]);
    }
    // 删除数组
    this.eles = [];
  }
  // 将Snake构造函数暴露出来
  window.Snake = Snake;
})();

// test
// var map = document.getElementById("map");
// var snake = new Snake();
// // console.log(snake.render);
// snake.render(map);